# -*- coding: utf-8 -*-

# Create your views here.
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.contrib import auth
from django.contrib import messages
from django.utils.translation import gettext
from django.http import HttpResponseRedirect
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate
from skran.public.form import LoginForm

"""
    Login function:
    
    This function receive an HTTP request. That can be an request of method GET, and it will 
    analyze if user is already authenticated or it can be an POST request. When it happen 
    user will authenticated in system, if user or login is not correct it will send 
    messages for interface informing error that occurred.
    
    @param request
"""
def login(request):
    
    login_form = LoginForm()
    
    if request.method == "GET":
        #If user is not authenticated it will render 
        if request.user.is_authenticated():
            return HttpResponseRedirect("projects")

    elif request.method == "POST":
        user = auth.authenticate(username=request.POST['email'],password=request.POST['password'])
        
        if user and user.is_active:
            auth.login(request,user)
            return HttpResponseRedirect("projects")
        
        else:
            messages.add_message(request,messages.ERROR,gettext("not_active"))
    else:
        messages.add_message(request,messages.ERROR,gettext("invalid_request"))
    
    return render_to_response('landpage.html',{'login_form':login_form},context_instance=RequestContext(request))

def do_authetication(request, username, password):
    if request is None:
        raise Exception("Chamada não definida!")
    
    if username and password:
        form = AuthenticationForm(data=request.POST)
        form.user_cache = authenticate(username=username, password=password)
        
        if form.user_cache is None:
            raise Exception("Por favor entre com um usuário e senha válidos.")
        elif not form.user_cache.is_active:
            raise Exception("Esta conta está inativa.")
        elif form.request and not form.request.session.test_cookie_worked():
            raise Exception("Aparentemente seu navegador não está autorizando o armazenamento de cookies. É necessário habilitar o armazenamento de cookies para realizar o login.")

        auth.login(request, form.user_cache)
    
        return form
    else:
        raise Exception("Há campos obrigatórios ainda não preenchidos!")


